%% calibration of spread

clear;
clc;



S_all=[55.15
16.58
13.05
11.87
11.18
10.82
10.43
10.49
11.16
11.18
10.68
10.64
10.36
29.92];

S_all=S_all/100;

S_data=S_all;

T_spread=length(S_data);



V_all2=[14.98
10.15
9.11
8.62
7.84
7.33
7.18
6.52
6.14
6.00
5.60
5.58
5.34
5.30
5.23
5.04
5.06
4.99
5.20
5.34
5.32
5.39
5.81
6.36
7.17
11.62];

V_all2=V_all2/100;



len=length(V_all2);

V_nas=zeros(len/2,1);

for t=1:len/2
    V_nas(t)=V_all2(2*t-1)+V_all2(2*t);
end

V_data=V_nas;


T_vol=length(V_data);







x0=[0.1643    0.1053   65.6038   15.8389    2.8554];   % N_M=1   N_I=2  tau_V=1  theta_bar=1
% [ alpha_0, alpha, beta, beta_T, lambda_I]=[ 0.1643    0.1053   65.6039   15.8388    2.8554]




F=@(x)sum((mySpread_RN(T_spread, x(1), x(2), x(3), x(4), x(5))-S_data([1,3,5,7,9,11,13,14])).^2)*1.5 ...
    +sum((myVol_RN(T_vol, x(1), x(2), x(3), x(4), x(5))-V_data([1,3,5,7,9,11,13])).^2)*1.0;



[xfunc, fval]= fminsearch(F, x0)



S_fit=mySpread_RN(T_spread, xfunc(1), xfunc(2), xfunc(3), xfunc(4), xfunc(5));



ts=0:1/(T_spread-1):1;

figure(1)
plot(ts, S_data, 'o', ts([1,3,5,7,9,11,13,14]), S_fit);
colororder(["r"; "#0072BD"])
legend('Emprical Average', 'Model Calibration', 'interpreter','latex')
xlabel('$t/T$','interpreter','latex')
ylabel('Expected Bid-Ask Spread', 'interpreter','latex')
ylim([0 0.6])



tv=1/T_vol:1/T_vol:1;

V_fit=myVol_RN(T_vol, xfunc(1), xfunc(2), xfunc(3), xfunc(4), xfunc(5));

figure(2)
plot(tv, V_data, 'o', tv([1,3,5,7,9,11,13]), V_fit);
colororder(["r"; "#0072BD"])
legend('Emprical Average', 'Model Calibration', 'interpreter','latex')
xlabel('$t/T$','interpreter','latex')
ylabel('Expected Turnover', 'interpreter','latex')
ylim([0.05 0.35])



